package com.igeek.web;

import com.igeek.domain.Cart;
import com.igeek.domain.CartItem;
import com.igeek.domain.Product;
import com.igeek.service.Productservice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/cart")
public class CartServlet extends BaseServlet {
    public void addCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收参数
        String quantity = request.getParameter("quantity");
        String pid = request.getParameter("pid");
        System.out.println(quantity+"--"+pid);
        //2.1构建cartitem对象
        CartItem item = new CartItem();
        //根据pid获取product
        Productservice service = new Productservice();
        Product p = service.getProductByPid(pid);
        item.setProduct(p);
        item.setBuyNum(Integer.parseInt(quantity));
        //2.2 构建Cart对象
        //假设session中存在一个购物车cart，从session中取出这个cart，
        //如果cart为null，说明第一次放物品，应该new cart
        //如果cart不为null，说明以前放过，应该在这个cart中添加商品
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
        }
        //往购物车中添加商品
        cart.addCatrItem(item);
        //2.3
        session.setAttribute("cart",cart);
        //3.跳转到cart.jsp
        //F5刷新后，forward会重复提交数据，改成重定向
        //request.getRequestDispatcher("cart.jsp").forward(request,response);
        response.sendRedirect("cart.jsp");
    }

    public  void delCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收参数
        String pid = request.getParameter("pid");
        //2.从session中取出购物车
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        //3.购物车删除商品
        cart.delelteCartItem(pid);
        //4.跳转到cart.jsp
        //request.getRequestDispatcher("cart.jsp").forward(request,response);
        response.sendRedirect("cart.jsp");
    }

    public  void delCartAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //2.从session中取出购物车
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        //3.购物车删除商品
        cart.delelteAll();
        //4.返回delSuccess字符串
        response.getWriter().write("delSuccess");
    }
}
